package com.friend.uu;

import android.content.Context;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.widget.Toast;

public class TorchUtils {
    private static Camera mCamera;

    //是否支持电筒功能
    private static boolean supportFlash(Context context) {
        PackageManager pm = context.getPackageManager();
        FeatureInfo[] afs = pm.getSystemAvailableFeatures();
        String flashFeature = PackageManager.FEATURE_CAMERA_FLASH;
        for (FeatureInfo fi : afs) {
            if (flashFeature.equals(fi.name)) {
                return true;
            }
        }
        Toast.makeText(context, "不支持手电筒", Toast.LENGTH_SHORT).show();
        return false;
    }

    //开关
    public static void torchToggle(Context context) {
        if (!supportFlash(context)) {
            return;
        }
        if (mCamera == null) {
            mCamera = Camera.open();
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            mCamera.setParameters(parameters);
        } else {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            mCamera.setParameters(parameters);
            mCamera.release();
            mCamera = null;
        }
    }
}
